#include "udpserver.hpp"
#include <memory>
#include <cstdio>
#include <vector>

void User(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " serverport[1024+]\n"
              << std::endl;
}

std::string Handler(const std::string &str)
{
    string ret = "server echo#";
    ret += str;

    return ret;
}

bool SafeCommand(const std::string &cmd)
{
    vector<std::string> bad_cmds={
        "rm",
        "kill",
        "touch",
        "top",
        "sleep",
        "yum",
        "sudo",
        "unlink",
        "uninstall"
    };

    for(auto &e:bad_cmds)
    {
        auto iter=cmd.find(e);

        //找到了
        if(iter!=string::npos) return false;
    }

    
    return true;
}

std::string ExcuteCommand(const std::string &cmd)
{
    // 检查命令的合法性
    if(!SafeCommand(cmd)) return "Bad man";

    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr)
    {
        perror("popen");
        return "error";
    }

    string ret;
    char buffer[4096];
    while (true)
    {
        // 读取子进程执行命令的结果
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr)
            break;
        ret += buffer;
    }

    pclose(fp);

    return ret;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        User(argv[0]);
        return 1;
    }
    uint16_t port = stoi(argv[1]);

    std::unique_ptr<udpServer> svr(new udpServer(port));

    svr->Init();
    svr->Run();

    return 0;
}